<template>
  <div class="employee-container">
    <!-- 头部导航 -->
    <header class="header">
      <div class="header-content">
        <h1>👥 员工管理</h1>
        <div class="header-actions">
          <button class="btn-back" @click="$router.push('/home')">🏠 返回首页</button>
          <button class="btn-logout" @click="handleLogout">🚪 退出</button>
        </div>
      </div>
    </header>

    <!-- 主内容 -->
    <main class="main-content">
      <!-- 操作栏 -->
      <div class="action-bar" v-if="userRole !== 'employee'">
        <button class="btn-primary" @click="showCreateDialog">➕ 创建员工</button>
        <div class="search-box">
          <select v-model="filterDeptId" @change="loadEmployees" v-if="userRole === 'admin'">
            <option value="">全部部门</option>
            <option v-for="dept in departments" :key="dept.id" :value="dept.id">
              {{ dept.name }}
            </option>
          </select>
        </div>
      </div>

      <!-- 员工列表 -->
      <div class="employee-list">
        <div v-if="loading" class="loading">⏳ 加载中...</div>
        
        <div v-else-if="employees.length === 0" class="empty">
          <p>暂无员工数据</p>
        </div>
        
        <div v-else class="employee-grid">
          <div v-for="emp in employees" :key="emp.id" class="employee-card">
            <div class="employee-header">
              <div class="employee-avatar">{{ emp.real_name ? emp.real_name[0] : emp.user[0] }}</div>
              <div class="employee-info">
                <h3>{{ emp.real_name || emp.user }}</h3>
                <span class="employee-role" :class="'role-' + emp.role">{{ emp.role_name }}</span>
              </div>
            </div>
            
            <div class="employee-details">
              <div class="detail-item">
                <span class="label">账号：</span>
                <span>{{ emp.user }}</span>
              </div>
              <div class="detail-item">
                <span class="label">部门：</span>
                <span>{{ emp.department_name || '未分配' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">邮箱：</span>
                <span>{{ emp.email || '未填写' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">状态：</span>
                <span :class="emp.status === 1 ? 'status-active' : 'status-inactive'">
                  {{ emp.status === 1 ? '✅ 正常' : '❌ 禁用' }}
                </span>
              </div>
            </div>
            
            <div class="employee-actions" v-if="canManageEmployee(emp)">
              <button class="btn-sm btn-edit" @click="showEditDialog(emp)">✏️ 编辑</button>
              <button 
                class="btn-sm btn-status" 
                @click="toggleStatus(emp)"
                v-if="emp.role !== 'admin'"
              >
                {{ emp.status === 1 ? '🚫 禁用' : '✅ 启用' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 创建/编辑对话框 -->
    <div v-if="showDialog" class="dialog-overlay" @click.self="closeDialog">
      <div class="dialog">
        <div class="dialog-header">
          <h3>{{ isEdit ? '✏️ 编辑员工' : '➕ 创建员工' }}</h3>
          <button class="btn-close" @click="closeDialog">✕</button>
        </div>
        
        <div class="dialog-body">
          <div class="form-group">
            <label>账号 *</label>
            <input v-model="form.user" :disabled="isEdit" placeholder="请输入账号">
          </div>
          
          <div class="form-group" v-if="!isEdit">
            <label>密码 *</label>
            <input v-model="form.password" type="password" placeholder="请输入密码（至少6位）">
          </div>
          
          <div class="form-group">
            <label>真实姓名</label>
            <input v-model="form.real_name" placeholder="请输入真实姓名">
          </div>
          
          <div class="form-group">
            <label>邮箱</label>
            <input v-model="form.email" type="email" placeholder="请输入邮箱">
          </div>
          
          <div class="form-group">
            <label>手机号</label>
            <input v-model="form.phone" placeholder="请输入手机号">
          </div>
          
          <div class="form-group">
            <label>部门 *</label>
            <select v-model="form.department_id">
              <option value="">请选择部门</option>
              <option v-for="dept in departments" :key="dept.id" :value="dept.id">
                {{ dept.name }}
              </option>
            </select>
          </div>
          
          <div class="form-group" v-if="userRole === 'admin'">
            <label>角色</label>
            <select v-model="form.role">
              <option value="employee">普通员工</option>
              <option value="manager">部门经理</option>
              <option value="admin">超级管理员</option>
            </select>
          </div>
        </div>
        
        <div class="dialog-footer">
          <button class="btn-secondary" @click="closeDialog">取消</button>
          <button class="btn-primary" @click="handleSubmit" :disabled="submitting">
            {{ submitting ? '⏳ 提交中...' : '✅ 确定' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="message" :class="['toast', messageType]">{{ message }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '../utils/request.js'

const router = useRouter()

// 状态
const userRole = ref(localStorage.getItem('user_role') || 'employee')
const currentUserId = ref(parseInt(localStorage.getItem('user_id')))
const employees = ref([])
const departments = ref([])
const loading = ref(false)
const showDialog = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const message = ref('')
const messageType = ref('info')
const filterDeptId = ref('')

// 表单数据
const form = ref({
  user: '',
  password: '',
  real_name: '',
  email: '',
  phone: '',
  department_id: '',
  role: 'employee'
})

onMounted(() => {
  loadDepartments()
  loadEmployees()
})

// 加载部门列表
const loadDepartments = async () => {
  try {
    const res = await request.get('/department/list')
    if (res.data.code === 200) {
      departments.value = res.data.data.departments
    }
  } catch (error) {
    console.error('加载部门失败:', error)
  }
}

// 加载员工列表
const loadEmployees = async () => {
  loading.value = true
  try {
    let url = '/employee/list'
    if (filterDeptId.value) {
      url += `?department_id=${filterDeptId.value}`
    }
    
    const res = await request.get(url)
    if (res.data.code === 200) {
      employees.value = res.data.data.employees
    }
  } catch (error) {
    console.error('加载员工失败:', error)
    showToast('加载员工列表失败', 'error')
  } finally {
    loading.value = false
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  form.value = {
    user: '',
    password: '',
    real_name: '',
    email: '',
    phone: '',
    department_id: '',
    role: 'employee'
  }
  showDialog.value = true
}

// 显示编辑对话框
const showEditDialog = (emp) => {
  isEdit.value = true
  form.value = {
    id: emp.id,
    user: emp.user,
    real_name: emp.real_name || '',
    email: emp.email || '',
    phone: emp.phone || '',
    department_id: emp.department_id || '',
    role: emp.role
  }
  showDialog.value = true
}

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false
}

// 提交表单
const handleSubmit = async () => {
  if (isEdit.value) {
    await updateEmployee()
  } else {
    await createEmployee()
  }
}

// 创建员工
const createEmployee = async () => {
  if (!form.value.user || !form.value.password) {
    showToast('请填写账号和密码', 'error')
    return
  }
  
  submitting.value = true
  try {
    const res = await request.post('/employee/create', form.value)
    if (res.data.code === 200) {
      showToast('创建成功', 'success')
      closeDialog()
      loadEmployees()
    }
  } catch (error) {
    showToast(error.response?.data?.message || '创建失败', 'error')
  } finally {
    submitting.value = false
  }
}

// 更新员工
const updateEmployee = async () => {
  submitting.value = true
  try {
    const res = await request.put(`/employee/update/${form.value.id}`, form.value)
    if (res.data.code === 200) {
      showToast('更新成功', 'success')
      closeDialog()
      loadEmployees()
    }
  } catch (error) {
    showToast(error.response?.data?.message || '更新失败', 'error')
  } finally {
    submitting.value = false
  }
}

// 切换状态
const toggleStatus = async (emp) => {
  const newStatus = emp.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '启用' : '禁用'
  
  if (!confirm(`确定要${action}员工 ${emp.real_name || emp.user} 吗？`)) return
  
  try {
    const res = await request.put(`/employee/status/${emp.id}`, { status: newStatus })
    if (res.data.code === 200) {
      showToast(`${action}成功`, 'success')
      loadEmployees()
    }
  } catch (error) {
    showToast(error.response?.data?.message || `${action}失败`, 'error')
  }
}

// 判断是否可以管理该员工
const canManageEmployee = (emp) => {
  if (userRole.value === 'admin') return true
  if (userRole.value === 'manager' && emp.role !== 'admin') return true
  if (userRole.value === 'employee' && emp.id === currentUserId.value) return true
  return false
}

// 退出登录
const handleLogout = async () => {
  if (!confirm('确定要退出登录吗？')) return
  
  try {
    await request.post('/user/logout')
  } catch (error) {
    console.error('退出失败:', error)
  } finally {
    localStorage.clear()
    router.push('/')
  }
}

// 显示提示消息
const showToast = (msg, type = 'info') => {
  message.value = msg
  messageType.value = type
  setTimeout(() => {
    message.value = ''
  }, 3000)
}
</script>

<style scoped>
.employee-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.header {
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.btn-back, .btn-logout {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: transform 0.2s;
}

.btn-back {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-logout {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.btn-back:hover, .btn-logout:hover {
  transform: translateY(-2px);
}

.main-content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.action-bar {
  background: white;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.btn-primary {
  padding: 10px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
}

.search-box select {
  padding: 10px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
}

.employee-list {
  background: white;
  padding: 20px;
  border-radius: 12px;
  min-height: 400px;
}

.loading, .empty {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  font-size: 16px;
}

.employee-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.employee-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  transition: transform 0.2s;
}

.employee-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.employee-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.employee-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: bold;
}

.employee-info h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.employee-role {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  margin-top: 4px;
}

.role-admin {
  background: #ffe5e5;
  color: #d63031;
}

.role-manager {
  background: #e3f2fd;
  color: #1976d2;
}

.role-employee {
  background: #e8f5e9;
  color: #388e3c;
}

.employee-details {
  margin-bottom: 16px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #e0e0e0;
  font-size: 14px;
}

.detail-item .label {
  color: #666;
  font-weight: 600;
}

.status-active {
  color: #28a745;
}

.status-inactive {
  color: #dc3545;
}

.employee-actions {
  display: flex;
  gap: 8px;
}

.btn-sm {
  flex: 1;
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 600;
}

.btn-edit {
  background: #667eea;
  color: white;
}

.btn-status {
  background: #f5576c;
  color: white;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 16px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow: auto;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.dialog-header h3 {
  margin: 0;
  font-size: 20px;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #555;
  font-size: 14px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  box-sizing: border-box;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #e0e0e0;
}

.btn-secondary {
  padding: 10px 20px;
  background: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
}

/* Toast消息 */
.toast {
  position: fixed;
  top: 80px;
  right: 20px;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: slideIn 0.3s ease-out;
  z-index: 1000;
}

@keyframes slideIn {
  from {
    transform: translateX(400px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.toast.success {
  background: #d4edda;
  color: #155724;
}

.toast.error {
  background: #f8d7da;
  color: #721c24;
}
</style>

